package androidApplication;

import security.Encryption;
import capstone.aw_capstone_androidapplication.R;
import entities.User;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Login extends Activity{
	private Commons common;
	
	private TextView txtUsername;
	private EditText pswPassword;
	private Button btnLogin;
	
	public Login(){
		
	}
	
	public void onCreate(Bundle b){
		super.onCreate(b);
		setContentView(R.layout.login);
		this.common = new Commons();
		new Thread(new Commons()).start();
		common.startClient();
		txtUsername = (TextView) findViewById(R.id.txtUsername);
		
		pswPassword = (EditText) findViewById(R.id.pswPassword);
		
		btnLogin = (Button) findViewById(R.id.btnLogin);
		btnLogin.setOnClickListener(btnLoginClicked);
		
	}
	
	private final Button.OnClickListener btnLoginClicked = new Button.OnClickListener(){
		@Override
		public void onClick(View arg0){			
			txtUsername = (TextView) findViewById(R.id.txtUsername);
			String username = (String) txtUsername.getText().toString();
			
			pswPassword = (EditText) findViewById(R.id.pswPassword);
			String password = (String) pswPassword.getText().toString();
			User user = common.getCsClient().getUser(username);
			if(Encryption.digest(password).equals(user.getPassword())){
				common.setUser(user);
				TelephonyManager tmanager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
				String UUID = tmanager.getDeviceId();
				
				WifiManager myWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
				WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
				int ipAddress = myWifiInfo.getIpAddress();
				String ip = android.text.format.Formatter.formatIpAddress(ipAddress);
				//
				common.getDeviceInfo(UUID, ip);
				Intent intent = new Intent(Login.this.getApplication(), MainOverview.class);
				intent.putExtra("Commons", common);
				startActivity(intent);
			}else{
				Intent intent = new Intent(Login.this.getApplication(), Login.class);
				startActivity(intent);
			}			
		}
	};
}
